import App from './App'
import MyPage from '@/components/MyPage.vue';
import store from './store'

function handlePage(url) {
	uni.navigateTo({
		url: url
	})
}

// 应用启动时检查令牌状态
function checkTokenOnLaunch() {
	// 应用启动时只负责检查和刷新令牌
	// 用户信息的获取由App.vue的onShow处理
	const token = uni.getStorageSync('user_token_key')
	if (token) {
		const loginTime = uni.getStorageSync('login_time_key')
		if (loginTime) {
			const currentTime = new Date().getTime()
			const diffHours = (currentTime - loginTime) / (1000 * 60 * 60)
			
			// 如果登录时间超过23小时，自动刷新令牌
			if (diffHours > 23) {
				console.log('Main.js: 令牌需要刷新')
				store.dispatch('user/refreshToken')
					.then(() => {
						console.log('Main.js: 令牌刷新成功')
					})
					.catch(() => {
						console.log('Main.js: 令牌刷新失败')
					})
			} else {
				console.log('Main.js: 令牌有效，不需要刷新')
			}
		}
	} else {
		console.log('Main.js: 无令牌，跳过刷新检查')
	}
}

// #ifndef VUE3
import Vue from 'vue'
import './uni.promisify.adaptor'
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
  ...App
})
app.config.globalProperties.handlePage = handlePage
app.component('MyPage', MyPage)
app.use(store)
app.$mount()
// 启动时检查
checkTokenOnLaunch()
// #endif

// #ifdef VUE3
import { createSSRApp } from 'vue'
export function createApp() {
  const app = createSSRApp(App)
  app.config.globalProperties.handlePage = handlePage
  app.component('MyPage', MyPage)
  app.use(store)
  // 启动时检查
  checkTokenOnLaunch()
  return {
    app
  }
}
// #endif